/**
 * @title 行内编辑
 * @parent 编辑 Editor
 * @description 可以对行进行编辑的表格
 */
import React, { Component } from "react";
import { Table, Button } from 'tinper-bee';
import StringEditCell from './StringEditCell.jsx';
import Popconfirm from 'bee-popconfirm';
import 'bee-popconfirm/build/Popconfirm.css';
import Modal from 'bee-modal';
import 'bee-modal/build/Modal.css';
import Switch from 'bee-switch';
import 'bee-switch/build/Switch.css';

import {
    vendorsDanger as danger,
    vendorsSuccess as success,
} from './../../../../utils/config';

import { isLink, deleteItem, enableItem, disableItem } from './../../const';

import './index.less';
let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if (cookieStr) {
    tenantId = cookieStr.split('=')[1];
}
// let tenantId = "x61tnmfx";
class TableList extends Component {
    constructor(props, context) {
        super(props);
        this.state = {
            isShowLinkModal: false, // 是否被引用提示框
            dataSource: props.dataSource, // 数据源
            currentIndex: null,
            deletePkArr: [], // 存储删除数组
        };
    }

    changeTableEditStatus = () => {
        this.props.changeTableEditStatus();
    }

    componentWillReceiveProps(nextProps) {
        let _this = this;
        this.dataBuffer = [...nextProps.dataSource];
        this.setState({ dataSource: this.dataBuffer }); // React会自动合并setState操作
        this.columns = [
            {
                title: "序号",
                dataIndex: "index",
                key: "index",
                className: "text-left",
                render: (text, record, index) => {
                    return (
                        <span>{index + 1}</span>
                    )
                }
            },
            {
                title: "编码",
                dataIndex: "code",
                key: "code",
                className: "text-left",
                render: (text, record, index) => {
                    return (
                        <StringEditCell
                            autoFocus={record.autoFocus || false}
                            colKey={"code"}
                            editable={nextProps.editable}
                            maxLength={20}
                            required
                            value={text}
                            onChange={this.onCellChange(index, "code")}
                        />
                    )
                }
            },
            {
                title: "里程碑名称",
                dataIndex: "name",
                key: "name",
                className: "text-left",
                render: (text, record, index) => (
                    <StringEditCell
                        colKey={"name"}
                        editable={nextProps.editable}
                        maxLength={50}
                        required
                        value={text}
                        onChange={this.onCellChange(index, "name")}
                    />
                )
            },
            {
                title: "启用状态",
                dataIndex: "enableStatus",
                key: "enableStatus",
                className: "text-left",
                render: (text, record, index) => {
                    let flag = text === 1 ? true : false;
                    return (
                        <span onClick={() => { _this.enableOrDisableItem(record, "enableStatus", flag, index) }}>
                            <Switch colors={nextProps.editable ? "default" : "primary"} checked={flag} disabled={nextProps.editable} />
                        </span>
                    )
                }
            },
            {
                title: "操作",
                dataIndex: "operate",
                key: "operate",
                width: 200,
                className: "text-left",
                render: (text, record, index) => {
                    return (
                        <div>
                            <span className={nextProps.editable ? "dn" : "dib operation-btn"} onClick={this.changeTableEditStatus}>修改</span>
                            {
                                _this.props.editable ? <span className="operation-btn" onClick={() => { _this.deleteItem(record, index) }}>删除</span>
                                :
                                <Popconfirm trigger="click" placement="right" content={"确定要删除该条目吗？"} onClose={() => { _this.deleteItem(record, index) }}>
                                    <span className="operation-btn">删除</span>
                                </Popconfirm>
                            }
                        </div>
                    )
                }
            },
        ];
    }

    // 启用、停用里程碑
    enableOrDisableItem = (record, key, flag, index) => {
        // 先更改数据源，展示动画效果，再执行请求动作
        if (this.props.editable) { return false; }
        this.dataBuffer[index][key] = flag ? 0 : 1;
        this.setState({ dataSource: this.dataBuffer });
        this.props.changeDataSource(this.dataBuffer, () => {
            setTimeout(() => {
                if (this.props.editable) return false; // 编辑态，不允许修改启用停用
                let _this = this;
                let postData = {
                    pkMilestone: record.pkMilestone,
                    code: record.code,
                    name: record.name,
                    pkTenant: tenantId,
                    changeFlag: record.changeFlag,
                    enableStatus: record.enableStatus === 0 ? 1 : 0 // 显示动画效果，手动更改后，该字段正好与结果相反
                };
                switch (postData.enableStatus) {
                    case 1: // 启用-->停用
                        disableItem(postData).then((res) => {
                            ajaxCallBack(res);
                        });
                        break;
                    case 0: // 停用-->启用
                        enableItem(postData).then((res) => {
                            ajaxCallBack(res);
                        });
                        break;
                    default:
                        break;
                }

                function ajaxCallBack(res) {
                    let { resultCode, result, exMsg } = res.data;
                    if (resultCode !== "busi_ex") {
                        _this.props.refresh(_this.props.keyword);
                    } else {
                        danger({ text: exMsg });
                    }
                }
            }, 300);
        });
    }

    deleteItem = (record, index) => {
        if (index === null) return;
        let postData = { pk: record.pkMilestone };
        if (postData.pk) {
            isLink(postData).then((res) => { // 校验该条目是否被引用
                let { resultCode, result, exMsg } = res.data;
                if (resultCode !== "busi_ex") {
                    if (result) { // 被引用，无法删除，提示用户
                        localStorage.setItem('deleteItem', JSON.stringify({ postData, index }));
                        this.setState({ isShowLinkModal: true });
                    } else { // 没有引用，直接删除
                        this.deleteAction(postData, index);
                    }
                } else {
                    danger({ text: exMsg });
                }
            });
        } else {
            this.deleteAction(postData, index);
        }
    }

    // 删除动作
    deleteAction = (data, index) => {
        if (data.pk) {
            if (this.props.editable) { // 编辑态
                this.dataBuffer.splice(index, 1);
                this.state.deletePkArr.push(data.pk);
                this.setState({ dataSource: this.dataBuffer, isShowLinkModal: false });
                this.props.changeDataSource(this.dataBuffer);
                this.props.changeDeleteArr(this.state.deletePkArr);
            } else {
                deleteItem(data).then((res) => {
                    let { resultCode, result, exMsg } = res.data;
                    if (resultCode !== "busi_ex") {
                        this.dataBuffer.splice(index, 1);
                        this.props.changeDataSource(this.dataBuffer);
                        this.setState({ dataSource: this.dataBuffer, isShowLinkModal: false }, () => success({ text: '删除成功' }));
                    } else {
                        this.setState({ isShowLinkModal: false }, () => danger({ text: exMsg }));
                    }
                });
            }
        } else { // 增行后未保存删除，直接删除
            this.dataBuffer.splice(index, 1);
            this.props.changeDataSource(this.dataBuffer);
            this.setState({ dataSource: this.dataBuffer, isShowLinkModal: false });
        }

    }

    onCellChange = (index, key) => value => {
        this.dataBuffer[index][key] = value;
        this.props.changeDataSource(this.dataBuffer);
    };

    handleRowHover = (index, record) => {
        this.currentRecord = record;
        this.setState({ currentIndex: index });
    };

    closeModal = () => {
        this.setState({ isShowLinkModal: false });
    }

    render() {
        const { dataSource } = this.state;
        const columns = this.columns;
        return (
            <div className="u-editable-table">
                <Table
                    className="editable-table"
                    data={dataSource}
                    columns={columns}
                    height={20}
                    onRowHover={this.handleRowHover}
                />
                <Modal
                    show={this.state.isShowLinkModal}
                    onHide={this.close} >
                    <Modal.Header closeButton>
                        <Modal.Title><span className="warning-text">警告</span></Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <p>该里程碑已被引用，无法删除！</p>
                    </Modal.Body>
                    <Modal.Footer>
                        <Button onClick={this.closeModal} bordered>确认</Button>
                    </Modal.Footer>
                </Modal>
            </div>
        );
    }
}

export default TableList;